package com.ufox.controller;


import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ufox.entity.*;
import com.ufox.service.ICartitemService;
import com.ufox.service.IOrdersService;
import com.ufox.service.IProductsService;
import com.ufox.utils.RedisUtils;
import com.ufox.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.Connection;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 优狐科技-www.hbufox.com
 * @since 2022-06-09
 */
@RestController
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private ICartitemService cartitemService;

    @Autowired
    private RedisUtils redisUtils;


    @PutMapping
    public Result addOrders(@RequestBody Orders orders, HttpServletRequest request) {

        User user = UserUtil.getUser(request, redisUtils);
        Map<Products, Integer> map = cartitemService.findSum(user.getId() + "");
        Set<Map.Entry<Products, Integer>> entries = map.entrySet();
        double sum = 0;
        for (Map.Entry<Products, Integer> entry : entries) {
            Products products = entry.getKey();
            Integer num = entry.getValue();
            sum += products.getPrice() * num;
        }
        orders.setMoney(sum);
        orders.setUserId(user.getId());
        String uuid = IdUtil.simpleUUID();
        orders.setId(uuid);
        ordersService.addOrders(orders);
        return Result.ok("生成订单成功", "");
    }


    //删除
    @DeleteMapping("/{id}")
    public Result delOrder(@PathVariable String id) {
        ordersService.deleteOrder(id);
        return Result.ok();
    }


    //支付后删除 并修改state = -1
    @GetMapping("/{id}")
    public Result updateOrder(@PathVariable String id) {
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getId, id);
        Orders orders = new Orders();
        orders.setState(-1);
        boolean b = ordersService.update(orders, wrapper);
        return  (b ? Result.ok() : Result.error("删除失败"));
    }

}
